from flask import Blueprint, render_template, jsonify, request
from flask_login import login_required, current_user
from applications.common.utils.rights import authorize
from applications.models import Article
from applications.models import Category
from applications.models import Tag
from applications.schemas import ArticleSchema
from sqlalchemy import desc
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.curd import get_one_by_id
from applications.common.utils.validate import str_escape
from applications.extensions import db
import json

bp = Blueprint('article', __name__, url_prefix='/article')


# 首页
@bp.get('/')
def index():
    user = current_user
    return render_template('blog/article/main.html', user=user)

# 文章数据
@bp.get('/data')
# @authorize("blog:article:main")
def data():
    limit = str_escape(request.args.get('limit', type=int))
    type = str_escape(request.args.get('type', type=str)) or ""
    if int(limit) > 1000 or int(limit) < 0:
        limit = 100
    title = str_escape(request.args.get('title', type=str))
    filters = []
    if title:
        filters.append(Article.name.contains(title))
    articles = Article.query.filter(*filters).order_by(desc(Article.id)).layui_paginate()
    return table_api(data=ArticleSchema(many=True).dump(articles), count=articles.total,limit=limit)


# 文章删除
@bp.delete('/remove/<int:id>')
@authorize("blog:article:remove", log=True)
def remove(id):
    r = Article.query.filter_by(id=id).update({"is_del": 1})
    db.session.commit()
    if not r:
        return fail_api(msg="资源删除失败")
    return success_api(msg="资源删除成功")


#文章增加
@bp.get('/add')
@authorize("blog:article:add", log=True)
def add():
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id))
    filters = [Tag.is_del==0]
    tags = Tag.query.filter(*filters).order_by(desc(Tag.id))
    return render_template('blog/article/add.html', categorys=categorys, tags=tags)


# 文章保存
@bp.post('/save')
@authorize("blog:article:add", log=True)
def save():
    req = request.get_json(force=True)
    title = str_escape(req.get("articleTitle"))
    content = str_escape(req.get("articleContent"))
    category_id = str_escape(req.get("articleCategoryId"))
    if category_id:
        category_id = int(category_id)
    else:
        category_id = 1
    article = Article(
        title=title,
        content=content,
        category_id=category_id,
        is_del=0
    )
    tag_ids = req.get("articleTagIds")
    if isinstance(tag_ids, str):
        tag_ids = json.loads(tag_ids)
    for tag_id in tag_ids:
        tag = db.session.query(Tag).get(tag_id)
        article.tag.append(tag)
    db.session.add(article)
    db.session.commit()
    return success_api(msg="成功")


# 文章编辑
@bp.get('/edit/<int:id>')
@authorize("blog:article:edit", log=True)
def edit(id):
    r = get_one_by_id(model=Article, id=id)
    article_tags = r.tag
    article_tag_ids = []
    for article_tag in article_tags:
        article_tag_ids.append(article_tag.id)
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id))
    filters = [Tag.is_del==0]
    all_tags = Tag.query.filter(*filters).order_by(desc(Tag.id))
    return render_template('blog/article/edit.html', article=r, 
                           categorys=categorys, article_tags=article_tags,
                           all_tags=all_tags, article_tag_ids=article_tag_ids
                           )

# 更新资源
@bp.put('/update')
@authorize("blog:article:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    article_id = req_json.get("articleId")
    # 查询要更新的文章
    article = db.session.query(Article).get(article_id)
    tag_ids = req_json.get("articleTagIds")
    if isinstance(tag_ids, str):
        tag_ids = json.loads(tag_ids)
    for tag in list(article.tag):
        article.tag.remove(tag)
    for tag_id in tag_ids:
        tag = db.session.query(Tag).get(tag_id)
        article.tag.append(tag)
    category_id = str_escape(req_json.get("articleCategoryId"))
    if category_id:
        category_id = int(category_id)
    else:
        category_id = 1
    is_del = str_escape(req_json.get("isDel"))
    if is_del:
        is_del = int(is_del)
    else:
        is_del = 0
    data = {
        "title": str_escape(req_json.get("articleTitle")),
        "content": str_escape(req_json.get("articleContent")),
        "category_id": category_id,
        "is_del": is_del
    }
    Article.query.filter_by(id=article_id).update(data)
    db.session.commit()
    return success_api(msg="更新资源成功")
